/*
-----------------------------------------------------------------------------
This source file is part of as4game
(ActionScript For Game Engine)
For the latest info, see http://as4game.googlecode.com

Copyright (c) 2000-2011 Hproof Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
package
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Matrix3D;
	import flash.geom.Rectangle;
	import flash.geom.Vector3D;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	
	import org.as4game.common.disp.FloatText;
	import org.as4game.common.utils.Fps;
	import org.as4game.common.utils.KeyboardState;
	import org.as4game.render3d.Render3D;
	import org.as4game.resource.anim.Animation;
	import org.as4game.resource.anim.AnimationState;
	import org.as4game.resource.anim.AnimationStateSet;
	import org.as4game.resource.bitmap.Material;
	import org.as4game.resource.manager.ResourceManager;
	import org.as4game.resource.mesh.Mesh;
	import org.as4game.resource.skeleton.Bone;
	import org.as4game.resource.skeleton.Skeleton;
	import org.as4game.scene3d.Camera;
	import org.as4game.scene3d.Entity;
	import org.as4game.scene3d.Node;
	import org.as4game.scene3d.Plane;
	import org.as4game.scene3d.Scene;
	import org.as4game.scene3d.SceneNode;
	import org.aswing.tree.PathPlaceHolder;
	import org.ext.loader.ogre.MeshSerializer;
	import org.ext.loader.ogre.OgreLoader;
	import org.ext.loader.ogre.SkeletonSerializer;
	
	/**
	 * TestRenderEntity
	 */
	public class TestRenderEntity extends Sprite
	{
		private const WIDTH:int = 900;
		private const HEIGHT:int = 500; 
		
		private var _fps:Fps;
		private var _info:FloatText;
		private var _render:Render3D;
		private var _scene:Scene;
		private var _camera:Camera;
		private var _keyState:KeyboardState;
		private var _entites:Vector.<Entity>
		private var _sword:Entity;
		
		//
		public function TestRenderEntity(){
			
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			initResource( "cat", next);
			
			function next():void{
				_render = new Render3D;
				_render.create( stage, initScene );
			}
		}
		
		// 初始化场景
		private function initScene( render3d:Render3D ):void{
			_fps = new Fps;
			addChild( _info = new FloatText );
			
			_scene = new Scene;
			
			_camera = new Camera;
			_camera.aspect = WIDTH / HEIGHT;
			_scene.root.addChild( new SceneNode(null, _camera ) );
			_camera.sceneNode.mLocalMatrix.appendTranslation(0, 0, 10);
			_camera.sceneNode.setLocalChanged();
			
			_keyState = new KeyboardState( stage );
			
			_entites = new Vector.<Entity>;
			for(var loop:int=0; loop<1; loop++){
			for(var i:int=0; i<40; i++){
				var x:int = +(i % 10) * 2;
				var z:int = -(i / 10) * 2;
				
				var e:Entity = createEntity( "dragon", "cat" );
				_entites.push( e );
				
				_scene.root.addChild( new SceneNode( null, e ) );
				e.sceneNode.mLocalMatrix.appendScale(1, -1, 1);
				e.sceneNode.mLocalMatrix.appendTranslation(x, 0, -z + loop * 2);
				e.sceneNode.setLocalChanged();
				
				if( e.hasSkeleton() ){
					var aniList:Vector.<Animation> = e.mSkeletonInstance.mSkeleton.mAnimationsList;
					var ani:Animation = aniList[ i % aniList.length ];
					e.getAnimationState( ani.mName ).setEnabled( true );
					if( i >= aniList.length ) break;
				}
			}
			}
			
			// back, idle, run1, walk
//			_entity.sceneNode.mLocalMatrix.appendScale(0.05, 0.05, 0.05);
//			_entity.getAnimationState( "run1" ).setEnabled( true ); 
			
//			_sword = createEntity( "sword", ID_SWORD );
//			_entity.attachObjectToBone( ID_SWORD_BIND, _sword );
			
			// start render
			stage.addEventListener( Event.ENTER_FRAME, onEnterFrame );
			stage.addEventListener( MouseEvent.MOUSE_DOWN, onMouseEvent);
			stage.addEventListener( MouseEvent.MOUSE_MOVE, onMouseEvent);
			stage.addEventListener( MouseEvent.MOUSE_WHEEL, onMouseEvent);
			stage.addEventListener( MouseEvent.DOUBLE_CLICK, onMouseEvent);
			stage.addEventListener( Event.RESIZE, onResize );
			onResize( null );
		}
		
		private function onResize(e:Event):void{
			_render.viewport = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight );
			_render.context3D.configureBackBuffer( stage.stageWidth, stage.stageHeight, 1, true);
			_camera.aspect = stage.stageWidth / stage.stageHeight;
		} 
		
		private var _mousex:int, _mousey:int;
		private function onMouseEvent(e:MouseEvent):void{
			switch( e.type ){
				case MouseEvent.MOUSE_DOWN:
					_mousex = e.stageX;
					_mousey = e.stageY;
					break;
				case MouseEvent.MOUSE_MOVE:
					if( e.buttonDown ){
						var dx:int = e.stageX - _mousex;
						var dy:int = e.stageY - _mousey;
						_mousex = e.stageX;
						_mousey = e.stageY;
						_camera.sceneNode.mLocalMatrix.prependRotation( dx , Vector3D.Y_AXIS );
						_camera.sceneNode.mLocalMatrix.prependRotation( -dy , Vector3D.X_AXIS);
						_camera.sceneNode.setLocalChanged();
					}
					break;
				case MouseEvent.MOUSE_WHEEL:
					_camera.sceneNode.mLocalMatrix.prependTranslation( 0, 0, -e.delta );
					_camera.sceneNode.setLocalChanged();
					break;
				case MouseEvent.DOUBLE_CLICK:
					_camera.sceneNode.mLocalMatrix.identity();
					_camera.sceneNode.mLocalMatrix.prependTranslation(0, 0, -10);
					_camera.sceneNode.setLocalChanged();
					break;
			}
		}
		
		private function onEnterFrame(e:Event):void{
			_fps.frameStart();
			_fps.updateStart();
			
			var m:Matrix3D = _keyState.getMoveMatrix( 0.2, 1 );
			_camera.sceneNode.mLocalMatrix.prepend( m );
			_camera.sceneNode.setLocalChanged();
			
			var time_pass:Number  = _fps.time_pass / 1000;
			for each(var ent:Entity in _entites ){
				ent.addAnimationTime( time_pass );
			}
			
			var passes:Array = _render.preRender( _scene );
			
			var vp:Matrix3D = _camera.sceneNode.mWorldMatrix.clone();
			vp.invert();
//			var p:Matrix3D = _camera.projection;
			var p:Matrix3D = Camera.makeRectangularProjection( -5, 5, -5, 5, -1000, 1000);
			vp.append( p );
				
			_fps.renderStart();
			_render.render( _scene, vp, passes );
			
			_fps.frameEnd();
			
			_info.text = [
				"[" + _render.context3D.driverInfo.split(" ")[0] + "]", 
				"FPS: " + _fps.fps,
				"TRI: " + _render.num_triangle, 
				"PASS: " + _render.num_pass, 
				"FRAME: " + _fps.frameRatio+ "%", 
				"UPDATE: " + _fps.updateRatio+ "%",  
				"RENDER: " + _fps.renderRatio + "%",
			].join("  ");
		}

		// ================================================================================
		// resource
		
		// 初始化资源
		private function initResource( id:String, next:Function ):void{
			var path:String = loaderInfo.url;
			path = path.substr( 0, path.lastIndexOf("/")+1 );
			path = path + "res/" + id + "/";
			OgreLoader.loadAll( path, [id], next );
			
		}
		
		// 建立实体
		private function createEntity( name:String, id:String ):Entity{
			return new Entity( name, id + ".mesh" );
		}
	}
}